<?php
namespace jy_teamshop;
defined('BY_JYA') or exit('error');
/*
	分销佣金
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		$this->order=$order;
		$member=$this->get('member',array('mid'=>$order['mid']),array('is_agent','agent_id','level_id'));
		if($member['agent_id']){
			$agent_id=$member['agent_id'];
			$this->lastlevel=pdo_getcolumn('jy_weishop_member_level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']),'level');
			$this->lastlevel_id=$member['level_id'];
			$this->maxlevel=$member['level'];
		}
		//自购升级
		$this->update('member',array('myorder_price +='=>$order['price']),array('mid'=>$order['mid']));
		$this->model('member')->update_agent_level($order['mid'],$order['id']);
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'plugin_name'=>$this->order['plugin_name']?:'',
			'commission_money'=>0,
			'area_money'=>0,
			'jifen'=>0,
			'createtime'=>TIMESTAMP,
		);
		//佣金计算方式，是否扣除运费
		if($this->setting['commissiontype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		if($member['agent_id']){
			$agent=$this->get('member',array('mid'=>$member['agent_id']));
			
		}
		//当分销层级大于0时，逐次寻找上级推荐人并计算佣金
		for($i=0;$i<9;$i++){
			if(!$agent_id){
				break;
			}
			$member=$this->get('member',array('mid'=>$agent_id));
			$level=pdo_get('jy_weishop_member_level',array('id'=>$member['level_id']));
			$agent_id=$member['agent_id'];
			$this->create_commission($member,$level);
			if($this->lastlevel < $level['level'] && $this->maxlevel < $level['level']){
				$this->create_cha($member);
			}
			$this->lastlevel=$level['level'];
			if($this->maxlevel<$level['level']){
				$this->maxlevel=$level['level'];
				$this->lastlevel_id=$member['level_id'];
			}
		}
		//生成分销订单
		$this->insert('order',$this->commission_order);
		if($order['sendtype']==3){
			$status=pdo_getcolumn('jy_weishop_order',array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']),'status');
			if($status==3){
				$this->order_complete($order);
			}
		}
		return true;
	}
	/*
		差额;
	*/
	function create_cha($agent,$level=array(),$mylevel_id=0){
		if(!$agent || !$agent['is_agent'] || $agent['stop']){
			return false;
		}
		$mylevel_id=$mylevel_id?:$this->lastlevel_id;
		$money=0;
		$red_money=0;
		$mymoney=0;
		$order_price=$this->commission_order['commission_price'];
		$remark=array(
				'level_id'=>$mylevel_id,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
		);
		if($this->order['goods']){
				foreach($this->order['goods'] as $goods){
					$total_price=$goods['total_price'];
					$goods['total']=$goods['total']?:1;
					$pinggoods=$this->get('goods',array('goods_id'=>$goods['goodsid']));
					//先检查是否存在商品独立分红规则，如果存在则对订单相应商品部分金额单独计算分红
					if($pinggoods['ignore']  || !$pinggoods['id']){
							$diyprice=array();
							if($pinggoods['ignore']){
								$order_price=$order_price-$total_price;
							}
							$this->needorder=true;
							continue;
					}else{
							$diyprice=$pinggoods['diyprice']?json_decode($pinggoods['diyprice'],true):array();
							foreach($diyprice as $dv){
								if($mylevel_id==$dv['level_id'] && $agent['ishehuo']==$dv['ishehuo']){
									$mymoney=$dv['price'];
									break;
								}
							}
							$mymoney=$mymoney?:$goods['price'];
							foreach($diyprice as $dv){
								if($agent['level_id']==$dv['level_id'] && $agent['ishehuo']==$dv['ishehuo']){
									$money +=($mymoney-$dv['price'])*$goods['total'];
									break;
								}
							}
					}
					$remark['goods_commission'][]=array('goods_id'=>$pinggoods['id'],'total_price'=>$total_price,'total'=>1,'commission_per'=>$goods_commission_per,'commission_money'=>$money);
				}
		}
		$remark['commission_money']=$money;
		if($money>0){
				$this->commission_order['commission_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'level'=>$level['level'],
					'ordersn'=>$this->commission_order['ordersn'],
					'money'=>$money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>0,
					'type'=>3,
				);
				$this->insert('commission',$new_commission);
		}
		return $agent['agent_id'];
	}
	/*
		级差分佣;
	*/
	function create_commission($agent,$level=array()){
		if($agent && $agent['is_agent'] && $agent['stop']==0){
			//相应会员存在且是分销商且状态正常			
			if(!$agent['level_id']){
				$default_set=$this->plugin_setting('default_level');
				$level_id=0;
				$commission_per=$default_set['levelfee'];
			}else{
				$level['commissions']=json_decode($level['commissions'],true);
				$level_id=$level['id'];
				$commission_per=$level['commissions']['levelfee'];
			}
			$money=0;
			$red_money=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);
			if($this->order['goods']){
				foreach($this->order['goods'] as $goods){
					$total_price=$goods['total_price'];
					$pinggoods=$this->get('goods',array('goods_id'=>$goods['goodsid']));
					//先检查是否存在商品独立分红规则，如果存在则对订单相应商品部分金额单独计算分红
					if($pinggoods['ignore']  || !$pinggoods['id']){
							$goods_commission=array();
							if($pinggoods['ignore']){
								$order_price=$order_price-$total_price;
							}
							$this->needorder=true;
							continue;
					}else{
							$goods_commission=$pinggoods['commissions']?json_decode($pinggoods['commissions'],true):array();
							foreach($goods_commission as $gv){
								if($agent['level_id']==$gv['level_id']){
									$goods_commission_per=$gv['commissions']['levelfee'];
									break;
								}
							}
					}
					$order_price=$order_price-$total_price;
					//团队奖励			
					if(substr($goods_commission_per,-1)=='%'){
							$goods_commission_money=intval($total_price*substr($goods_commission_per,0,-1))/100;
							$goods_commission_money -=$this->commission_order['commission_money'];
							$money+=$goods_commission_money;
					}else{
							$goods_commission_money=$goods_commission_per;
							$goods_commission_money -=$this->commission_order['commission_money'];
							$money+=$goods_commission_money;
					}
					$remark['goods_commission'][]=array('goods_id'=>$pinggoods['id'],'total_price'=>$total_price,'total'=>1,'commission_per'=>$goods_commission_per,'commission_money'=>$goods_commission_money);
				}
			}
			if($order_price>0 && $this->needorder){
				if(substr($commission_per,-1)=='%'){
					$order_commission_money=intval($order_price*substr($commission_per,0,-1))/100;
					$order_commission_money -=$this->commission_order['commission_money'];
					$money+=$order_commission_money;
				}else{
					$order_commission_money=$commission_per;
					$order_commission_money -=$this->commission_order['commission_money'];
					$money+=$order_commission_money;
				}
				$remark['order_commission']=array('order_price'=>$order_price,'commission_per'=>$commission_per,'commission_money'=>$order_commission_money);
			}
			$remark['commission_money']=$money;
			//团队奖励
			if($money>0){
				$this->commission_order['commission_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'level'=>$level['level'],
					'ordersn'=>$this->commission_order['ordersn'],
					'money'=>$money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>0,
					'type'=>0,
				);
				$this->insert('commission',$new_commission);
				$member_update=array(
					'order_price'=>$agent['order_price']+$this->commission_order['order_price'],
					'order_num'=>$agent['order_num']+1,
				);
				$this->update('member',$member_update,array('mid'=>$agent['mid']));
			}
		}
		//如果他的上级是我
		$ta_agent_id=$this->getcolumn('member',array('mid'=>$agent['agent_id']),'agent_id');
		if($ta_agent_id==$agent_id){
			return false;
		}
		return $agent['agent_id'];
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>1,'ordersn'=>$order['ordersn']));
		$list=$this->getall('commission',array('ordersn'=>$order['ordersn']));
		foreach($list as $info){
			if($info['jifen']>0){
				model('core/member')->add_credit1($info['mid'],$info['jifen'],'佣金兑积分','jy_teamshop');
			}
		}
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid='',$pay_trade_no=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			//exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'pay_trade_no'=>$trade_no=='pay_trade_no'?$pay_trade_no:$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		if($pay_type){
			$update['pay_type']=$pay_type;
		}
		$this->update('balance',$update,array('id'=>$balance['id']));
		$this->model('notice')->notice_fenxiao_dakuan($balance['mid'],$balance['final_money']);
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_teamshop_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['commission_level']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
	/*
		获取单独商品佣金
	*/
	protected function get_goodsfee($goodsid,$orderid,$ordergoodsid=''){
		$ordersn=pdo_getcolumn('jy_weishop_order',array('id'=>$orderid,'uniacid'=>$_SESSION['uniacid']),'ordersn');
		$commissionremark=$this->pdo_getcolumn('commission',array('ordersn'=>$ordersn,'uniacid'=>$_SESSION['uniacid']),'remark');
		//print_r($ordersn.'~~'.$commissionremark);exit;
		$commissionremark=json_decode($commissionremark,true);
		
		$goodsfee=0;
		if($commissionremark['goods_commission']){
			foreach($commissionremark['goods_commission'] as $gv){
				if($ordergoodsid){
					if($ordergoodsid==$gv['ordergoodsid']){
						$goodsfee +=$gv['commission_money'];
					}
				}else{
					if($goodsid==$gv['goods_id']){
						$goodsfee +=$gv['commission_money'];
					}
				}
			}
		}
		if($commissionremark['order_commission'] && $goodsfee==0){
			$allorderfee=pdo_getsum('jy_weishop_order_goods',array('orderid'=>$orderid,'goodsid'=>$goodsid),'total_price');
			//exi($allorderfee.'~'.$commissionremark['order_commission']['order_price'].'~'.$commissionremark['order_commission']['commission_money'],'error');
			$goodsfee=($allorderfee/$commissionremark['order_commission']['order_price'])*$commissionremark['order_commission']['commission_money'];
		}
		return $goodsfee;
	}
}